<?php

declare(strict_types=1);

namespace App\Models;

use App\Services\LocationService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;

class Area extends Model
{
    public $timestamps  = false;
    protected $table    = 'area';
    protected $fillable = [
        'id',
        'areaname',
        'level',
        'parentid',
        'is_open',
    ];

    /**
     * id 和 areaname 的 map
     * return array
     */
    public static function getRootCitysAsMap()
    {
        $map   = [];
        $areas = static::where('parentid', '=', 0)
            ->where('is_open', '=', 1)
            ->get();
        foreach ($areas as $area) {
            $map[$area->id] = $area->areaname;
        }

        return $map;
    }

    public function getCity($cityID)
    {
        $cities = $this->getCities();
        if (isset($cities[$cityID])) {
            return $cities[$cityID];
        }

        return false;
    }

    public function getCities($parentID = 0)
    {
        $cacheData = Redis::get(config('cache.CACHE_PREFIX') . 'city_roots_' . $parentID);
        if (empty($cacheData)) {
            $cacheData = $this->getAllRoots($parentID);
            Redis::set(config('cache.prefix') . 'city_roots_' . $parentID, json_encode($cacheData));
        } else {
            $cacheData = json_decode($cacheData);
        }

        return $cacheData;
    }

    public function getAllRoots($parentID = 0)
    {
        return $this->select(['id', 'areaname'])
            ->where('parentid', '=', $parentID)
            ->where('is_open', '=', 1)
            ->get()
            ->keyBy('id')
            ->toArray();
    }

    public function products()
    {
        return $this->hasMany(CityProducts::class, 'city_id', 'id');
    }

    public static function getAllRootsWithUnopened()
    {
        $roots = static::where(['parentid' => 0, 'level' => 1])->get();

        return $roots;
    }

    public static function getAllOpenAreaIds()
    {
        $res = static::select(['id'])->where(['is_open' => 1])->get();
        $res = $res ? (array) array_column($res->toArray(), 'id') : [];

        return $res;
    }

    public static function getAllOpenDistrictAreasIdsWithDashes()
    {
        $res  = LocationService::getCityData(0, true);
        $data = [];
        if (is_array($res)) {
            foreach ($res as $k => $row) {
                $data[] = $row->a1id . '-' . $row->a2id;
            }
        }

        return (array) array_values((array) array_unique($data));
    }

    //获取一个城市及其下属所有的area.id
    public static function getCityChildAreaIds(int $cityId)
    {
        $ids   = $idArr   = [];
        $query = static::select(['a1.id as lv2id', 'a2.id as lv3id'])->
        from('area as a1')->
        leftJoin('area as a2', 'a1.id', 'a2.parentid')->
        where(['a1.parentid' => $cityId])->get();
        if ($query) {
            $idArr = $query->toArray();
            if ($idArr) {
                $lv2Ids = array_column($idArr, 'lv2id');
                $lv3Ids = array_column($idArr, 'lv3id');
                $ids    = array_merge([$cityId], $lv2Ids, $lv3Ids);
                $ids    = array_values(array_unique($ids));
            }
        }

        return $ids;
    }

    //开启或关闭指定一批area
    public static function toggleAreas(array $areaIds, int $isOpen)
    {
        $upd = static::whereIn('id', $areaIds)->update(['is_open' => $isOpen]);

        return is_int($upd);
    }

    public static function getCityDistricts($cityId = 0)
    {
        $where = [
            'parentid' => $cityId,
            'level'    => 2,
        ];
        $data = static::select(['id', 'areaname'])->where($where)->get();
        $data = $data ? $data->toArray() : [];

        return $data;
    }
}
